package cn.tedu.knows.portal.service.impl;

import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.mapper.QuestionTagMapper;
import cn.tedu.knows.portal.mapper.UserMapper;
import cn.tedu.knows.portal.mapper.UserQuestionMapper;
import cn.tedu.knows.portal.model.*;
import cn.tedu.knows.portal.mapper.QuestionMapper;
import cn.tedu.knows.portal.service.IQuestionService;
import cn.tedu.knows.portal.service.ITagService;
import cn.tedu.knows.portal.service.IUserService;
import cn.tedu.knows.portal.vo.QuestionVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2022-03-04
 */
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private UserMapper userMapper;


    @Override
    public PageInfo<Question> getMyQuestions(String username, Integer pageNum, Integer pageSize) {
        User user = userMapper.findUserByUsername(username);
        QueryWrapper<Question> query = new QueryWrapper<>();
        query.eq("user_id", user.getId());
        query.eq("delete_status", 0);
        query.orderByDesc("createtime");

        PageHelper.startPage(pageNum, pageSize);

        List<Question> list = questionMapper.selectList(query);
        for (Question question : list) {
            List<Tag> tags = tagNamesToTags(question.getTagNames());
            question.setTags(tags);
        }
        return new PageInfo<>(list);
    }


    @Autowired
    private ITagService tagService;

    private List<Tag> tagNamesToTags(String tagNames) {
        String[] names = tagNames.split(",");
        Map<String, Tag> tagMap = tagService.getTagMap();
        List<Tag> tags = new ArrayList<>();
        for (String name : names) {
            Tag t = tagMap.get(name);
            tags.add(t);
        }
        return tags;
    }

    @Autowired
    private IUserService userService;
    @Autowired
    private QuestionTagMapper questionTagMapper;
    @Autowired
    private UserQuestionMapper userQuestionMapper;


    @Override
    @Transactional
    public void saveQuestion(QuestionVO questionVO, String username) {
        User user=userMapper.findUserByUsername(username);
        StringBuilder builder=new StringBuilder();
        for (String tagName:questionVO.getTagNames()){
            builder.append(tagName+",");
        }
        builder.deleteCharAt(builder.length()-1);
        String tagNames=builder.toString();

        Question question=new Question()
                .setTitle(questionVO.getTitle())
                .setContent(questionVO.getContent())
                .setUserNickName(user.getNickname())
                .setUserId(user.getId())
                .setCreatetime(LocalDateTime.now())
                .setStatus(0)
                .setPageViews(0)
                .setPublicStatus(0)
                .setDeleteStatus(0)
                .setTagNames(tagNames);
        int num=questionMapper.insert(question);
        if (num!=1){
            throw new ServiceException("数据库异常");
        }
        Map<String,Tag>tagMap=tagService.getTagMap();
        for (String tagName:questionVO.getTagNames()){
            Tag t=tagMap.get(tagName);
            QuestionTag questionTag=new QuestionTag()
                    .setQuestionId(question.getId())
                    .setTagId(t.getId());
            num=questionTagMapper.insert(questionTag);
            if (num!=1){
                throw new ServiceException("数据库异常");
            }
            log.debug("新增问题和标签的关系:{}",questionTag);
        }
        Map<String,User>teacherMap = userService.getTeacherMap();
        for (String nickName: questionVO.getTeacherNicknames()){
            User teacher=teacherMap.get(nickName);
            UserQuestion userQuestion=new UserQuestion()
                    .setUserId(teacher.getId())
                    .setQuestionId(question.getId())
                    .setCreatetime(LocalDateTime.now());

            num=userQuestionMapper.insert(userQuestion);
            if (num!=1){
                throw new ServiceException("数据库异常");
            }
            log.debug("新增问题和标签的关系:{}",userQuestion);
        }

    }

    @Override
    public PageInfo<Question> getTeacherQuestions(String username, Integer pageNum, Integer pageSize) {
        User user=userMapper.findUserByUsername(username);
        PageHelper.startPage(pageNum,pageSize);
        List<Question>list=questionMapper.findTeacherQuestions(user.getId());
        for (Question question:list){
            List<Tag> tags=tagNamesToTags(question.getTagNames());
            question.setTags(tags);
        }
        return new PageInfo<>(list);
    }

    @Override
    public Question getQuestionById(Integer id) {
        Question question=questionMapper.selectById(id);
        List<Tag> tags=tagNamesToTags(question.getTagNames());
        question.setTags(tags);
        return question;
    }

}
